package cn.face;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.util.concurrent.ArrayBlockingQueue;

public class FaceService extends Service {

    private FaceBinder faceBinder;
    boolean running=false;
    Thread runTaskThread;
    boolean isInit=false;
    private Object lock=new Object();
    volatile boolean wait=false;
    String TAG=getClass().getSimpleName();
    ArrayBlockingQueue<Task> taskQueue=new ArrayBlockingQueue(100);
    public FaceService() {
    }


    @Override
    public void onCreate() {
        super.onCreate();
        running=true;
        Log.e(TAG,"onCreate");
        runTaskThread=new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG,"task run");
                while (running){
                    try {
                        Task task=taskQueue.take();
                        Log.e(TAG,"runTask take");
                        task.run();
                        Log.e(TAG,"runTask run done");
                        wait=false;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.e(TAG,"task stop");
            }
        });
        runTaskThread.start();
        faceBinder=new FaceBinder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return faceBinder;
    }

    @Override
    public void onDestroy() {
        running=false;
        runTaskThread.interrupt();
        super.onDestroy();
    }



    public class FaceBinder extends Binder{
        public void auth() {
            if (isInit) return;

        }


        public void stop(){
            running=false;
            if(runTaskThread!=null){
                runTaskThread.interrupt();
            }
        }

        public void addTask(Task task){
            try {
                taskQueue.put(task);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void runTask(Task task){
            try {
                wait=true;
                taskQueue.put(task);
                long t=System.currentTimeMillis();
                while(wait&&System.currentTimeMillis()-t<10000)
                    Thread.sleep(50);
                Log.e(TAG,"runTask done");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public interface Task{
        void run();
    }
}
